#pragma once
#include<iostream>
#include<string>
#include"Log.hpp"
#include"Init.hpp"

// extern Log lg;

Init init; //全局变量

class Task{
public:
    Task(int sockfd,const std::string &clientip, const uint16_t &clientport)
    :sockfd_(sockfd),clientip_(clientip),clientport_(clientport){        
    }
    Task(){}
    void run(){
        // test code
        char buffer[4096];
        // Tcp面向字节流的,如何保证读取数据是一个完整报文?
        ssize_t n = read(sockfd_,buffer,sizeof(buffer));
        if(n>0){
            buffer[n] = 0;
            std::cout<<"client key# "<<buffer<<std::endl;
            std::string echo_string = init.tranlation(buffer);
            std::cout<<"client key# "<<echo_string<<std::endl;
            n = write(sockfd_,echo_string.c_str(),echo_string.size());//写入?
            if(n<0){
                lg(Warning, "write error, errno: %d, errstring: %s",errno,strerror(errno));
            }
        }else if(n==0){
            lg(Info,"%s,%d quit, server close sockfd: %d",clientip_.c_str(),clientport_,sockfd_);
        }else{
            lg(Warning,"read error,sockfd: %d,client ip:%s, client port: %d", sockfd_,clientip_.c_str(),clientport_);
        }
    }

    void operator()(){
        run();
    }
    ~Task(){}
private:
    int sockfd_;
    std::string clientip_;
    uint16_t clientport_;
};
